package com.example.graduation.util;

import com.example.graduation.exception.MyException;
import com.example.graduation.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * ProjectName graduation
 *
 * @author xieyucan
 * <br>CreateDate 2022/2/12 11:29
 */
@Slf4j
@Component
public class EmailSender {

    /**
     * 发送者邮箱号码
     */
    @Value("${spring.mail.username}")
    private String username;

    @Resource
    private JavaMailSender sender;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private UserMapper userMapper;

    /**
     * 生成六位数验证码
     *
     * @return {@link String}
     * @author xieyucan
     * CreateDate 2022/2/12 11:50
     */
    public String createCode() {
        Random random = new Random();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int num = random.nextInt(10);
            builder.append(num);
        }
        String code = builder.toString();
        log.info("生成验证码为：{}", code);
        return code;
    }

    /**
     * 生成验证码
     *
     * @param email
     * @return {@link String}
     * @author xieyucan
     * CreateDate 2022/2/12 11:58
     */
    public String sendCode(String email) {
        try {
            if (PhoneOrEmailUtil.isEmail(email)) {
                Integer count = userMapper.countEmail(email);
                if (count == 1) {
                    SimpleMailMessage mailMessage = new SimpleMailMessage();
                    mailMessage.setFrom(username);
                    mailMessage.setTo(email);
                    mailMessage.setSubject("斜雨山-商城");
                    String code = createCode();
                    String text = "亲爱的购物商城用户您好,您的邮箱验证码为：" + code + "，邮箱验证码的有效时间为5分钟，请注意有效时间和验证码的保密";
                    mailMessage.setText(text);
                    String key = "xyc_" + email;
                    sender.send(mailMessage);
                    redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);
                    log.info("邮箱发送成功");
                    return code;
                } else {
                    log.info("邮箱不存在");
                    throw new MyException("邮箱不存在");
                }
            } else {
                log.info("邮箱格式输入不正确");
                throw new MyException("邮箱输入格式不正确");
            }
        } catch (MyException e) {
            log.error("邮箱发送失败：{}", e);
            throw new MyException(e.getMsg());
        }
    }
}
